package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.service.EmailService;
import cn.edu.lingnan.service.UserService;
import cn.edu.lingnan.user.dtos.Result;
import cn.edu.lingnan.user.pojos.User;
import cn.edu.lingnan.user.vos.UserInfoVo;
import cn.edu.lingnan.user.vos.UserVO;
import cn.edu.lingnan.utils.JwtUtils;
import cn.edu.lingnan.utils.RegexUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Override
    @Async
    public void sendCode(String to) {
        if (!RegexUtils.isValidEmail(to)) {
            log.info("邮箱格式错误：{}", to);
            return;
        }

        String code = RandomUtil.randomNumbers(6);

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom("考拉考试系统 <13414863534@163.com>"); // 发件人名称+邮箱
            helper.setTo(to);
            helper.setSubject("【考拉考试系统】登录验证码");

            // 构建 HTML 邮件内容
            String htmlContent = buildEmailHtmlContent(code);
            helper.setText(htmlContent, true); // true 表示内容是 HTML

            mailSender.send(message);

            String key = "login:code:" + to;
            redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
            log.info("验证码发送成功，邮箱：{}", to);
        } catch (MessagingException e) {
            log.error("邮件发送失败：{}", e.getMessage());
        }
    }


    @Override
    public Result loginEmail(String email, String code, HttpSession session) {
        if(!RegexUtils.isValidEmail(email)){
            log.info("邮箱是{}",email);
            return Result.error("邮箱格式错误");
        }
        //从redis中获取验证码
        String key="login:code:"+email;
        String redisCode = redisTemplate.opsForValue().get(key);
        if(!code.equals(redisCode)){
            return Result.error("验证码错误");
        }
        //根据邮箱查询用户
        UserInfoVo userInfoVo= userMapper.getUserByEmail(email);
        if(userInfoVo==null){
            return Result.error("用户不存在,请注册");
        }
        if(userInfoVo.getStatus()==0){
            return Result.error("用户已被禁用");
        }

         // 准备 JWT
        String jwt = JwtUtils.generateJwt(Map.of(
                "userId", userInfoVo.getUserId(),
                "userName", userInfoVo.getUserName()
        ));

        // 设置 Token 到 UserInfoVo
        userInfoVo.setToken(jwt);
        userInfoVo.setDelFlag(null);
        userInfoVo.setUserPassword(null);
        userInfoVo.setSalt(null);



        //删除redis中的验证码
        redisTemplate.delete(key);

        return  Result.success(userInfoVo);
    }

    @Override
    public Result sendRegisterCode(String email) {
        if(!RegexUtils.isValidEmail(email)){
            log.info("邮箱是{}",email);
            return Result.error("邮箱格式错误");
        }
        //检查该邮箱是否已注册
        UserInfoVo userInfoVo= userMapper.getUserByEmail(email);
        if(userInfoVo!=null){
            log.info("邮箱是{}",email);
            return  Result.error("该邮箱已注册");
        }
        String code = RandomUtil.randomNumbers(6);
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom("考拉考试系统 <13414863534@163.com>"); // 发件人名称+邮箱
            helper.setTo(email);
            helper.setSubject("【考拉考试系统】注册验证码");

            // 构建 HTML 邮件内容
            String htmlContent = buildEmailHtmlContent(code);
            helper.setText(htmlContent, true); // true 表示内容是 HTML
            mailSender.send(message);
        }
        catch (MessagingException e) {
            log.error("邮件发送失败：{}", e.getMessage());
        }

        String key = "register:code:" + email;
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
        log.info("验证码发送成功，邮箱：{}", email);
        return Result.success("验证码发送成功");
    }

    @Override
    public Result sendResetPasswordCode(String email) {
         if(!RegexUtils.isValidEmail(email)){
            log.info("邮箱是{}",email);
            return Result.error("邮箱格式错误");
        }
        UserInfoVo userByEmail = userMapper.getUserByEmail(email);
         if(userByEmail==null){
            return Result.error("该邮箱未注册");
        }
         String code = RandomUtil.randomNumbers(6);
         try {
             MimeMessage message = mailSender.createMimeMessage();
             MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
             helper.setFrom("考拉考试系统 <13414863534@163.com>");
             helper.setTo(email);
             helper.setSubject("【考拉考试系统】重置密码验证码");

             //构建HTML邮件内容
             String htmlContent = buildEmailHtmlContent(code);
             helper.setText(htmlContent, true);
             mailSender.send(message);
         } catch (MessagingException e) {
             log.error("邮件发送失败：{}", e.getMessage());
         }
         String key = "reset:code:" + email;
         redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
         log.info("验证码发送成功，邮箱：{}", email);
         return Result.success("验证码发送");

    }

    // 构建 HTML 邮件模板
    private String buildEmailHtmlContent(String code) {
        return "<!DOCTYPE html>" +
                "<html style=\"font-family: Arial, sans-serif;\">" +
                "<head>" +
                "    <meta charset=\"UTF-8\">" +
                "</head>" +
                "<body style=\"margin: 0; padding: 20px; background-color: #f5f5f5;\">" +
                "    <div style=\"max-width: 600px; margin: 20px auto; background: white; border-radius: 8px; padding: 30px;\">" +
                "        <div style=\"text-align: center; margin-bottom: 30px;\">" +
                "            <img src=\"https://a1.qpic.cn/psc?/V52X7WVc0zxbh33LMtrc4TkJuJ1L0GJs/LiySpxowE0yeWXwBdXN*SXgR*8aLL2eNpVoRyzoWMlJCSgaDkKAgdtA2YOpiBi3FrpuB33PpHlnCEjGGA7tDE2aHAHpBhxwB*LkeoiEDVlU!/c&ek=1&kp=1&pt=0&bo=DAOaAgwDmgIDNxI!&tl=1&vuin=663341747&tm=1741766400&dis_t=1741769515&dis_k=ee99279bbfc145048122f328df7a573b&sce=60-2-2&rf=0-0\" alt=\"考拉考试系统\" style=\"height: 50px;\">" +
                "        </div>" +
                "        <h2 style=\"color: #2d3e50; text-align: center; margin-bottom: 30px;\">您的验证码</h2>" +
                "        <div style=\"background-color: #f8f9fa; padding: 20px; border-radius: 6px; text-align: center;\">" +
                "            <p style=\"font-size: 16px; color: #666; margin: 0;\">验证码：</p>" +
                "            <p style=\"font-size: 32px; color: #1890ff; font-weight: bold; margin: 10px 0;\">" + code + "</p>" +
                "            <p style=\"font-size: 14px; color: #999;\">（5分钟内有效）</p>" +
                "        </div>" +
                "        <div style=\"margin-top: 30px; text-align: center; color: #666; font-size: 14px;\">" +
                "            <p>如非本人操作，请忽略此邮件。</p>" +
                "            <p>© 2025 考拉考试系统</p>" +
                "        </div>" +
                "    </div>" +
                "</body>" +
                "</html>";
    }


}
